package com.mybatisflex.demo.service.impl;

import com.mybatisflex.annotation.UseDataSource;
import com.mybatisflex.core.datasource.DataSourceKey;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.demo.entity.Account;
import com.mybatisflex.demo.mapper.AccountMapper;
import com.mybatisflex.demo.service.AccountService;
import com.mybatisflex.spring.service.impl.CacheableServiceImpl;
import org.apache.ibatis.cursor.Cursor;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.List;

/**
 * @author 王帅
 * @since 2023-08-13
 */
@Service
@UseDataSource("ds2")
@CacheConfig(cacheNames = "account")
@SuppressWarnings("all")
public class AccountServiceImpl extends CacheableServiceImpl<AccountMapper, Account> implements AccountService {

    // ================= 缓存测试 ==================

    @Override
    @Cacheable(key = "#id")
    public Account getById(Serializable id) {
        return super.getById(id);
    }

    @Override
    @CacheEvict(key = "#entity.id")
    public boolean updateById(Account entity) {
        return super.updateById(entity);
    }

    @Override
    @Cacheable(key = "#root.methodName + ':' + #query.toSQL()")
    public Account getOne(QueryWrapper query) {
        return super.getOne(query);
    }

//    @Override
//    public QueryWrapper query() {
//        return QueryWrapper.create().from(ACCOUNT);
//    }

    // ================== 游标测试 =================

    @Override
    @Transactional
    public void findAllByCursor() {
        Cursor<Account> accounts = mapper.selectCursorByQuery(QueryWrapper.create());
        for (Account account : accounts) {
            System.out.println(account);
        }
    }

    // ================== 事务测试 =================

    @Override
    @Transactional
    public boolean save(Account entity) {
        super.save(entity);
//        throw new RuntimeException();
        return false;
    }

    // ================= 多数据源测试 ==================

    @Override
    @UseDataSource("ds3")
    public List<Account> list() {
        try {
//            FlexDataSource dataSource = FlexGlobalConfig.getDefaultConfig().getDataSource();
//            dataSource.removeDatasource("ds5");
            DataSourceKey.use("ds5");
            return super.list();
        } finally {
            DataSourceKey.clear();
        }
    }

    // ================== 数据权限测试 =================

    @Override
    public List<Account> list(QueryWrapper query) {
//        Account loginUser = LoginManager.getLoginUser();
//        query.and(ACCOUNT.DEPT_ID.eq(loginUser.getDeptId()));
        return super.list(query);
    }

}